<template>
    <BasicLayout>
        <template #wrapper>
            <el-card class="box-card">
                <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">

                    <!--                    <el-form-item label="服务ID" prop="serviceId">-->
                    <!--                        <el-input v-model="queryParams.serviceId" placeholder="请输入服务ID" clearable size="small"-->
                    <!--                            @keyup.enter.native="handleQuery" />-->
                    <!--                    </el-form-item>-->
                    <el-form-item label="订单号" prop="tradeSn">
                        <el-input v-model="queryParams.tradeSn" placeholder="请输入支付订单号，支付成功后记录" clearable size="small"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="订单状态" prop="tradeStatus">
                        <el-select v-model="queryParams.tradeStatus" placeholder="订单状态" clearable size="small">
                            <el-option v-for="dict in tradeStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                                :value="dict.dictValue" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="订单来源"prop="orderFrom">
                        <el-select v-model="queryParams.orderFrom" placeholder="订单来源" clearable size="small">
                            <el-option v-for="dict in orderFromOptions" :key="dict.dictValue" :label="dict.dictLabel"
                                       :value="dict.dictValue" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="queryParams.phone" placeholder="请输入下单手机号" clearable size="small"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="核销时间" prop="payAt">
                        <el-date-picker v-model="queryParams.payAt" value-format="yyyy-MM-dd" type="daterange"
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="small">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="下单时间" prop="createdAt">
                        <el-date-picker v-model="queryParams.createdAt" value-format="yyyy-MM-dd" type="daterange"
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="small">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-permisaction="['edu:order:add']" type="primary" icon="el-icon-plus" size="mini"
                            @click="handleAdd">新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-permisaction="['edu:order:edit']" type="success" icon="el-icon-edit" size="mini"
                            :disabled="single" @click="handleUpdate">修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-permisaction="['edu:order:remove']" type="danger" icon="el-icon-delete" size="mini"
                            :disabled="multiple" @click="handleDelete">删除
                        </el-button>
                    </el-col>
                </el-row>

                <el-table v-loading="loading" :data="eduorderList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="手机号" align="center" prop="phone" :show-overflow-tooltip="true" />

                    <el-table-column label="服务" width="200px" align="center" prop="remark"
                        :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="item in scope.row.itemList" class="row ali_cen" :key="item.serviceId">
                                <el-image style="width: 30px; height:30px;margin-right:10px" :src="item.cover">
                                </el-image>
                                <div style="margin-right:10px">{{item.title}}*{{item.num}}</div>
                                <div>￥{{item.price}}</div>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column label="订单总价" align="center" prop="totalPrice" :show-overflow-tooltip="true" />

                    <el-table-column label="抵扣金额" align="center" prop="deductionPrice" :show-overflow-tooltip="true" />
                    <el-table-column label="店铺信息" width="200px" align="center" prop="remark"
                        :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <!--                            <div v-for="item in scope.row.storeInfo" class="row ali_cen" :key="item.storeId">-->
                            <el-image style="width: 30px; height:30px;margin-right:10px"
                                :src="scope.row.storeInfo.avatar">
                            </el-image>
                            <div style="margin-right:10px">{{scope.row.storeInfo.storeName}}</div>

                            <!--                            </div>-->
                        </template>
                    </el-table-column>
                    <el-table-column label="实际支付金额" align="center" prop="payPrice" :show-overflow-tooltip="true" />
                    <el-table-column label="订单号" align="center" prop="orderNumber" :show-overflow-tooltip="true" />

                    <el-table-column label="订单状态" align="center" prop="tradeStatus" :formatter="tradeStatusFormat"
                        width="100">
                        <template slot-scope="scope">
                            {{ tradeStatusFormat(scope.row) }}
                        </template>
                    </el-table-column>
                    <!--                    <el-table-column label="下单时间" align="center" prop="createdAt" :show-overflow-tooltip="true" />-->
                    <!--                    <el-table-column label="支付时间" align="center" prop="payAt" :show-overflow-tooltip="true" />-->
                    <el-table-column label="预约到店时间" align="center" prop="appointmentTime"
                        :show-overflow-tooltip="true" />

                    <el-table-column label="管理员备注" align="center" prop="remark" :show-overflow-tooltip="true" />

                    <el-table-column label="操作" align="center" width="150px" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button v-permisaction="['edu:order:edit']" size="mini" type="text" icon="el-icon-edit"
                                @click="handleUpdate(scope.row)">修改
                            </el-button>
                            <el-button v-permisaction="['edu:order:verification']" size="mini" type="text" icon="el-icon-edit"
                                @click="handlePut(scope.row)">核销
                            </el-button>
                            <el-button v-permisaction="['edu:order:remove']" size="mini" type="text"
                                icon="el-icon-delete" @click="handleDelete(scope.row)">取消
                            </el-button>
                            <el-button v-permisaction="['edu:order:qrCode']" size="mini" type="text"
                                icon="el-icon-picture-outline" @click="handleImage(scope.row)">订单二维码</el-button>
                            <el-button v-permisaction="['edu:order:pay']" size="mini" type="text"
                                icon="el-icon-picture-outline" @click="AdminPay(scope.row)">立即支付</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageIndex"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />

                <!-- 添加或修改对话框 -->
                <el-dialog :title="title" :visible.sync="open" width="500px">
                    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                        <!-- <el-form-item label="交易关闭时间" prop="closeAt">
              <el-input v-model="form.closeAt" placeholder="交易关闭时间" />
            </el-form-item>
            <el-form-item label="抵扣金额" prop="deductionPrice">
              <el-input v-model="form.deductionPrice" placeholder="抵扣金额" />
            </el-form-item>
            <el-form-item label="备注" prop="mark">
              <el-input v-model="form.mark" placeholder="备注" />
            </el-form-item>
            <el-form-item label="订单号" prop="orderNumber">
              <el-input v-model="form.orderNumber" placeholder="订单号" />
            </el-form-item>
            <el-form-item label="支付时间" prop="payAt">
              <el-date-picker
                v-model="form.payAt"
                type="datetime"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="实际支付金额" prop="payPrice">
              <el-input v-model="form.payPrice" placeholder="实际支付金额" />
            </el-form-item>
            <el-form-item label="支付方式" prop="payType">
              <el-radio-group v-model="form.payType">
                <el-radio
                  v-for="dict in payTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="管理员备注" prop="remark">
              <el-input v-model="form.remark" placeholder="管理员备注" />
            </el-form-item>
            <el-form-item label="卖家id" prop="serviceId">
              <el-input v-model="form.serviceId" placeholder="卖家id" />
            </el-form-item>
            <el-form-item label="订单总价" prop="totalPrice">
              <el-input v-model="form.totalPrice" placeholder="订单总价" />
            </el-form-item>
            <el-form-item label="支付交易号，支付成功后记录" prop="tradeSn">
              <el-input
                v-model="form.tradeSn"
                placeholder="支付交易号，支付成功后记录"
              />
            </el-form-item>
            <el-form-item
              label="订单状态:created;paid;cancelled;refound"
              prop="tradeStatus"
            >
              <el-radio-group v-model="form.tradeStatus">
                <el-radio
                  v-for="dict in tradeStatusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="购买者" prop="userId">
              <el-input v-model="form.userId" placeholder="购买者" />
            </el-form-item> -->
                        <el-form-item label="手机号" prop="phone">
                            <el-autocomplete v-model="form.phone" :disabled="form.orderId"
                                :fetch-suggestions="querySearchAsync" placeholder="请输入手机号"></el-autocomplete>
                        </el-form-item>
                        <el-form-item label="选择服务">
                            <el-select v-model="form.serviceId" :disabled="form.orderId" placeholder="选择服务" multiple
                                @change="changeService">
                                <el-option v-for="item in serviceList" :key="item.serviceId" :label="item.title"
                                    :value="item.serviceId">
                                </el-option>
                            </el-select>
                            <div v-for="item in currentServiceList" :key="item.serviceId" style="margin-top:10px"
                                class="row ali_cen ju_bet">
                                <div>{{item.title}}（￥{{item.price}}）</div>
                                <el-input-number @change="changeNum" v-model="item.num" :min="1" label="描述文字"
                                    size="mini"></el-input-number>
                            </div>
                        </el-form-item>
                        <el-form-item label="选择门店">
                            <el-select v-model="form.storeId" :disabled="form.orderId" placeholder="请选择门店">
                                <el-option v-for="item in storeList" :key="item.storeId" :label="item.storeName"
                                    :value="item.storeId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="选择时间">

                            <el-date-picker v-model="form.appointmentTime" :disabled="form.orderId"
                                value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                        <!--                        <el-form-item label="付款金额" prop="phone" v-if="form.orderId">-->
                        <!--                            <el-input v-model="form.payPrice" placeholder="请输入付款金额"></el-input>-->
                        <!--                        </el-form-item>-->
                        <el-form-item label="付款金额" prop="price" v-if="form.orderId">
                            <el-input-number v-model="form.payPrice" :precision="2" :step="0.1" :min="0">
                            </el-input-number>
                        </el-form-item>
                        <el-form-item label="抵扣方式" prop="score">
                            <el-radio-group v-model="form.isUseScore">
                                <el-radio key="T" label="T">积分抵扣
                                </el-radio>
                                <el-radio key="F" label="F">优惠券
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="优惠券" v-if="form.isUseScore != 'T'">
                            <el-select v-model="form.couponId" :disabled="form.orderId" placeholder="请选择优惠券">
                                <el-option v-for="item in couponList" :key="item.couponId" :label="item.couponName"
                                    :value="item.couponId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitForm">确 定</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </div>
                </el-dialog>
                <!-- 渠道二维码 对话框-->
                <el-dialog :title="title_image" :visible.sync="open_image" width="500px">
                    <iframe v-show="open_image" id="show-iframe" frameborder="0" name="showHere" scrolling="auto"
                        :src="imageUrl" style="height:600px;width:100%"></iframe>
                </el-dialog>
                <!-- 直接支付 -->
                <el-dialog :title="payTitle" :visible.sync="payOpen" width="500px">
                    <el-form ref="form" :model="form2" :rules="rules" label-width="80px">
                        <el-form-item label="支付密码" prop="telephone">
                            <el-input v-model="form2.pws" placeholder="支付密码" show-password
                                :style="{ width: '195px' }" />
                        </el-form-item>
                        <!--                        <el-form-item label="支付密码" prop="orderId">-->
                        <!--                            <el-input v-model="form.orderId" placeholder="支付密码" :style="{ width: '195px' }" />-->
                        <!--                        </el-form-item>-->

                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="handAdminPay">确 定</el-button>
                        <el-button @click="cancelPay">取 消</el-button>
                    </div>
                </el-dialog>
            </el-card>
        </template>
    </BasicLayout>
</template>
<style lang="scss" scoped>
.el-select,
.el-autocomplete,
.el-input {
    width: 100%;
}
</style>
<script>
import {
    addEduOrder,
    delEduOrder,
    getEduOrder,
    listEduOrder,
    updateEduOrder,
} from "@/api/edu/finance/order";
import {
    listgeneralUser,
    getgeneralUser,
    delgeneralUser,
    addgeneralUser,
    updategeneralUser,
} from "@/api/generaluser";
import { serviceList, storeList, postOrder, putOrder, putUseOrder, putAdminPay, userCouponList } from '@/api/user';
export default {
    name: "Config",
    data () {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            isEdit: false,
            //渠道二维码路径
            imageUrl: "",
            // 渠道二维码弹出层标题
            title_image: "",
            payTitle: "",
            // 是否显示渠道二维码弹出层
            open_image: false,
            payOpen: false,
            payOrderId: 0,
            // 类型数据字典
            typeOptions: [],
            eduorderList: [],
            payTypeOptions: [],
            tradeStatusOptions: [],
            orderFromOptions: [],
            // 查询参数
            queryParams: {
                pageIndex: 1,
                pageSize: 10,
                orderId: undefined,
                serviceId: undefined,
                tradeSn: undefined,
                tradeStatus: undefined,
                orderFrom: undefined,
                userId: undefined,
                phone: undefined,
                createdAt: undefined,
                payAt: undefined,
            },
            // 表单参数
            form: {
                isUserBalance: 'T',
                isUseScore: 'T',
            },
            // 表单参数
            form2: {
                pws: "",
            },
            // 表单校验
            rules: {
                orderId: [{ required: true, message: "不能为空", trigger: "blur" }],
                serviceId: [
                    { required: true, message: "卖家id不能为空", trigger: "blur" },
                ],
                tradeSn: [
                    {
                        required: true,
                        message: "支付交易号，支付成功后记录不能为空",
                        trigger: "blur",
                    },
                ],
                tradeStatus: [
                    {
                        required: true,
                        message: "订单状态:created;paid;cancelled;refound不能为空",
                        trigger: "blur",
                    },
                ],
                userId: [
                    { required: true, message: "购买者不能为空", trigger: "blur" },
                ],
            },
            serviceList: [],
            storeList: [],
            currentServiceList: [],
            totalMoney: 0,
            couponList: []
        };
    },
    watch: {
        'form.phone': {
            deep: true,
            handler () {
                console.log(this.form.phone)
                if (this.form.phone) {
                    userCouponList(this.form.phone).then(res => {
                        this.couponList = res.data.list
                    })
                }

            },
        }
    },
    created () {
        this.getList();
        this.getDicts("edu_pay_type").then((response) => {
            this.payTypeOptions = response.data;
        });

        this.getDicts("edu_trade_status").then((response) => {
            this.tradeStatusOptions = response.data;
        });
        this.getDicts("order_from").then((response) => {
            this.orderFromOptions = response.data;
        });
        // serviceList().then(res => {
        //     this.serviceList = res.data.list
        // })
        serviceList({ pageSize: 1000 }).then(res => {
            this.serviceList = res.data.list
        })
        storeList().then(res => {
            this.storeList = res.data.list;
            this.form.storeId = this.storeList[0].storeId
        })
    },
    methods: {
        querySearchAsync (queryString, cb) {
            // console.log(queryString)
            listgeneralUser({
                phone: queryString
            }).then(res => {
                let ary = []
                if (res.data.list) {
                    res.data.list.forEach(item => {
                        ary.push({
                            value: item.phone
                        })
                    })
                }
                cb(ary)
            })
        },

        changeNum (e) {
            console.log(e)
        },
        changeService (e) {
            let currentServiceList = [];
            let service = [];

            if (this.currentServiceList) {
                currentServiceList = this.currentServiceList
                currentServiceList.forEach((item, i) => {
                    if (e.indexOf(item.serviceId) < 0) {
                        currentServiceList.splice(i, 1)
                    }
                })
            }
            this.serviceList.forEach(item => {
                if (e.indexOf(item.serviceId) >= 0) {
                    let ary = currentServiceList.filter(val => {
                        return val.serviceId == item.serviceId
                    })
                    if (!ary.length) {
                        currentServiceList.push({
                            num: 1,
                            serviceId: item.serviceId,
                            title: item.title,
                            price: item.price
                        })
                    }
                }
            })
            this.currentServiceList = currentServiceList
        },
        /** 查询参数列表 */
        getList () {
            this.loading = true;
            listEduOrder(this.addDateRange(this.queryParams, this.dateRange)).then(
                (response) => {
                    this.eduorderList = response.data.list;
                    this.total = response.data.count;
                    this.loading = false;
                }
            );
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                isUserBalance: 'T',
                isUseScore: 'T',
            };
            this.currentServiceList = [];
            this.form.storeId = this.storeList[0].storeId
            this.resetForm("form");
        },
        payTypeFormat (row) {
            return this.selectDictLabel(this.payTypeOptions, row.payType);
        },
        tradeStatusFormat (row) {
            return this.selectDictLabel(this.tradeStatusOptions, row.tradeStatus);
        },
        orderFromFormat (row) {
            return this.selectDictLabel(this.orderFromOptions, row.orderFrom);
        },

        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageIndex = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            this.open = true;
            this.title = "添加订单";
            this.isEdit = false;
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map((item) => item.orderId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            console.log(row)
            if (row.tradeStatus != 'created') {
                this.$message.error('未付款的订单才可以修改')
                return false
            }
            this.reset();
            const orderId = row.orderId || this.ids;
            getEduOrder(orderId).then((response) => {
                this.form = response.data
                let currentServiceList = [];
                let serviceId = [];
                row.itemList.forEach(item => {
                    currentServiceList.push(item)
                    if (serviceId.indexOf(item.serviceId) < 0) {
                        serviceId.push(item.serviceId)
                    }
                })
                this.currentServiceList = currentServiceList;
                this.form.serviceId = serviceId
                this.open = true;
                this.title = "修改订单";
                this.isEdit = true;
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.form.goods = this.currentServiceList;
                    console.log(this.form)
                    if (this.form.orderId !== undefined) {
                        let form = {
                            payPrice: this.form.payPrice,
                            orderId: this.form.orderId,
                        }
                        putOrder(form).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    } else {
                        postOrder(this.form).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    }
                }
            });
        },
        // 核销
        handlePut (row) {
            // console.log(row)
            this.$confirm('是否对核销该笔订单', '系统提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                putUseOrder(row.orderId, {
                    orderId: row.orderId,
                    usedAt: this.formatDate(new Date())
                }).then(res => {
                    this.$message.success(res.msg);
                })
            })
        },

        //查看渠道二维码
        handleImage (row) {
            this.title_image = row.phone + "的二维码";

            this.open_image = true;

            const orderId = row.orderId;
            this.imageUrl =
                "https://cli.im/api/qrcode/code?text=https://mini.amian.vip/order?orderId=" +
                orderId;
        },
        formatDate (time) {
            let date = new Date(time).valueOf();
            let now = new Date();
            let year = new Date(time).getFullYear().toString().padStart(2, '0');
            let mon = (new Date(time).getMonth() + 1).toString().padStart(2, '0');
            let timeDate = new Date(time).getDate()
            let day = timeDate.toString().padStart(2, '0');
            let h = new Date(time).getHours().toString().padStart(2, '0');
            let m = new Date(time).getMinutes().toString().padStart(2, '0');
            let s = new Date(time).getSeconds().toString().padStart(2, '0');
            return `${year}-${mon}-${day} ${h}:${m}:${s}`
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            if (row.tradeStatus != 'created') {
                this.$message.error('未付款的订单才可以取消')
                return false
            }
            const Ids = row.orderId || this.ids;
            this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(function () {
                    return delEduOrder(Ids);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(function () { });
        },
        /** 立即支付 */
        AdminPay (row) {
            if (row.tradeStatus != 'created') {
                this.$message.error('未付款的订单才立即支付')
                return false
            }
            if (row.payPrice != 0) {
                this.$message.error('支付金额为0的订单才能立即支付')
                return false
            }
            this.payTitle = "请输入支付密码";

            this.payOpen = true;
            this.payOrderId = row.orderId;
            const orderId = row.orderId;
        },
        /** 立即支付 */
        handAdminPay () {

            let form2 = {
                pws: this.form2.pws,
                orderId: this.payOrderId,
            }
            putAdminPay(form2).then((response) => {
                if (response.code === 200) {
                    this.msgSuccess("修改成功");
                    this.payOpen = false;
                    this.getList();
                } else {
                    this.msgError(response.msg);
                }
            });
        },
        // 取消支付
        cancelPay () {
            this.payOpen = false;
            this.reset();
        },
    },
};
</script>
